#!/bin/bash

# Matrix Framework 开发环境设置脚本
# 在网络问题的情况下，创建开发模拟环境

echo "🚀 Matrix Framework 开发环境设置"
echo "===================================="

# 检查必要的工具
echo "📋 检查开发工具..."

# 检查Node.js
if command -v node &> /dev/null; then
    NODE_VERSION=$(node --version)
    echo "✅ Node.js: $NODE_VERSION"
else
    echo "❌ Node.js 未安装，请先安装 Node.js 16+"
    exit 1
fi

# 检查npm
if command -v npm &> /dev/null; then
    NPM_VERSION=$(npm --version)
    echo "✅ npm: $NPM_VERSION"
else
    echo "❌ npm 未安装"
    exit 1
fi

# 检查.NET
if command -v dotnet &> /dev/null; then
    DOTNET_VERSION=$(dotnet --version)
    echo "✅ .NET: $DOTNET_VERSION"
else
    echo "❌ .NET 未安装，请先安装 .NET 8 SDK"
    exit 1
fi

echo ""
echo "🏗️ 创建开发环境结构..."

# 创建前端开发目录
mkdir -p src/web/frontend
mkdir -p src/web/frontend/src/{components,pages,services,store,utils}
mkdir -p src/web/frontend/public

# 创建模拟的Keycloak主题目录（用于开发测试）
mkdir -p src/platform-services/Keycloak/themes/matrix/login/{css,js,img}
mkdir -p docker/keycloak/realms

echo "✅ 目录结构创建完成"

echo ""
echo "📝 创建开发配置文件..."

# 创建前端开发配置
cat > src/web/frontend/package.json << 'EOF'
{
  "name": "matrix-frontend",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "test": "vitest",
    "test:ui": "vitest --ui"
  },
  "dependencies": {
    "vue": "^3.4.0",
    "vue-router": "^4.2.0",
    "pinia": "^2.1.0",
    "axios": "^1.6.0",
    "element-plus": "^2.4.0",
    "@element-plus/icons-vue": "^2.3.0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.5.0",
    "vite": "^5.0.0",
    "typescript": "^5.3.0",
    "@vue/tsconfig": "^0.4.0",
    "vitest": "^1.0.0",
    "@vue/test-utils": "^2.4.0"
  }
}
EOF

# 创建Vite配置
cat > src/web/frontend/vite.config.ts << 'EOF'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        changeOrigin: true
      },
      '/keycloak': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/keycloak/, '')
      }
    }
  },
  resolve: {
    alias: {
      '@': '/src'
    }
  }
})
EOF

# 创建TypeScript配置
cat > src/web/frontend/tsconfig.json << 'EOF'
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
EOF

echo "✅ 前端配置文件创建完成"

echo ""
echo "🎨 创建模拟的Keycloak登录页面..."

# 创建模拟的Keycloak登录页面HTML
cat > src/web/frontend/public/mock-keycloak-login.html << 'EOF'
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Matrix Framework - 登录</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-container {
            background: white;
            padding: 3rem;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 420px;
        }

        .logo {
            text-align: center;
            margin-bottom: 2rem;
        }

        .logo img {
            width: 80px;
            height: 80px;
            border-radius: 12px;
            margin-bottom: 1rem;
        }

        .logo h1 {
            font-size: 1.8rem;
            color: #333;
            font-weight: 300;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #555;
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .login-btn {
            width: 100%;
            padding: 1rem;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .login-btn:hover {
            transform: translateY(-2px);
        }

        .login-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .error {
            color: #dc3545;
            margin-bottom: 1rem;
            padding: 0.75rem;
            background: rgba(220, 53, 69, 0.1);
            border-radius: 8px;
            display: none;
        }

        .success {
            color: #28a745;
            margin-bottom: 1rem;
            padding: 0.75rem;
            background: rgba(40, 167, 69, 0.1);
            border-radius: 8px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">
            <h1>Matrix Framework</h1>
            <p style="color: #666;">企业级业务管理平台</p>
        </div>

        <div id="error" class="error"></div>
        <div id="success" class="success"></div>

        <form id="loginForm">
            <div class="form-group">
                <label for="username">用户名或邮箱</label>
                <input type="text" id="username" name="username" required>
            </div>

            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" required>
            </div>

            <button type="submit" class="login-btn" id="loginBtn">
                登录
            </button>
        </form>
    </div>

    <script>
        document.getElementById('loginForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            const errorDiv = document.getElementById('error');
            const successDiv = document.getElementById('success');
            const loginBtn = document.getElementById('loginBtn');

            // 隐藏之前的消息
            errorDiv.style.display = 'none';
            successDiv.style.display = 'none';

            // 禁用按钮
            loginBtn.disabled = true;
            loginBtn.textContent = '登录中...';

            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            try {
                // 模拟认证延迟
                await new Promise(resolve => setTimeout(resolve, 1000));

                // 模拟登录验证（实际应该调用Keycloak API）
                if (username === 'admin' && password === 'matrix_admin_2024') {
                    successDiv.textContent = '登录成功！正在跳转...';
                    successDiv.style.display = 'block';

                    // 模拟跳转
                    setTimeout(() => {
                        alert('登录成功！\n\n实际环境中这里会跳转到Matrix Framework主界面');
                        window.location.href = '/dashboard.html';
                    }, 1500);
                } else {
                    throw new Error('用户名或密码错误');
                }
            } catch (error) {
                errorDiv.textContent = error.message;
                errorDiv.style.display = 'block';
            } finally {
                loginBtn.disabled = false;
                loginBtn.textContent = '登录';
            }
        });
    </script>
</body>
</html>
EOF

echo "✅ 模拟登录页面创建完成"

echo ""
echo "🔧 创建开发启动脚本..."

# 创建开发启动脚本
cat > scripts/start-dev.sh << 'EOF'
#!/bin/bash

# Matrix Framework 开发环境启动脚本

echo "🚀 启动Matrix Framework开发环境..."

# 检查是否在项目根目录
if [ ! -f "package.json" ] && [ ! -f "Directory.Build.props" ]; then
    echo "❌ 请在项目根目录运行此脚本"
    exit 1
fi

# 启动前端开发服务器
echo "📱 启动前端开发服务器..."
cd src/web/frontend

# 检查是否安装了依赖
if [ ! -d "node_modules" ]; then
    echo "📦 安装前端依赖..."
    npm install
fi

echo "🌐 前端开发服务器启动在 http://localhost:3000"
echo "📝 模拟登录页面: http://localhost:3000/mock-keycloak-login.html"
echo "🔑 测试账户: admin / matrix_admin_2024"

npm run dev
EOF

chmod +x scripts/start-dev.sh

echo "✅ 开发启动脚本创建完成"

echo ""
echo "📝 创建API模拟服务..."

# 创建简单的API模拟服务
cat > scripts/mock-api.js << 'EOF'
// Matrix Framework API模拟服务
const express = require('express');
const cors = require('cors');

const app = express();
const PORT = 5000;

app.use(cors());
app.use(express.json());

// 健康检查
app.get('/health', (req, res) => {
    res.json({ status: 'healthy', timestamp: new Date().toISOString() });
});

// 模拟租户管理API
app.get('/api/tenant-management/tenants', (req, res) => {
    res.json([
        {
            id: 'default-tenant',
            name: 'default-tenant',
            displayName: '默认租户',
            keycloakRealm: 'MatrixFramework',
            isActive: true
        }
    ]);
});

// 模拟用户管理API
app.post('/api/user-system/auth/login', (req, res) => {
    const { username, password } = req.body;

    if (username === 'admin' && password === 'matrix_admin_2024') {
        res.json({
            accessToken: 'mock-jwt-token',
            refreshToken: 'mock-refresh-token',
            tokenType: 'Bearer',
            expiresIn: 3600,
            user: {
                id: 'admin-id',
                username: 'admin',
                email: 'admin@matrixframework.com',
                name: 'Admin',
                surname: 'User'
            },
            permissions: ['*'],
            roles: ['MATRIX_ADMIN']
        });
    } else {
        res.status(401).json({ error: '用户名或密码错误' });
    }
});

app.listen(PORT, () => {
    console.log(`🚀 Matrix Framework Mock API Server running on port ${PORT}`);
    console.log(`📊 Health check: http://localhost:${PORT}/health`);
    console.log(`🔗 API endpoint: http://localhost:${PORT}/api/`);
});

module.exports = app;
EOF

echo "✅ API模拟服务创建完成"

echo ""
echo "🎉 开发环境设置完成！"
echo "========================"
echo ""
echo "📋 接下来的步骤："
echo "1. 运行 'chmod +x scripts/start-dev.sh'"
echo "2. 运行 './scripts/start-dev.sh' 启动前端开发服务器"
echo "3. 访问 http://localhost:3000 查看应用"
echo "4. 访问 http://localhost:3000/mock-keycloak-login.html 测试登录"
echo ""
echo "📖 更多信息请查看："
echo "- README.md: 项目说明"
echo "- docs/guides/: 详细指南"
echo "- src/platform-services/Keycloak/themes/: Keycloak主题文件"
echo ""
echo "🚀 开始开发吧！"